
const router = require('koa-router')();
const bcrypt = require("bcrypt")
const jwt = require("jsonwebtoken")
const AdminUser = require("../../models/AdminUser")

router.post('/api/admin/login', async (ctx) => {
    // 1. 根据 username 找用户
    const { username, password } = ctx.request.body
    const user = await AdminUser.findOne({ username }).select('+password')
    ctx.assert(user, 422, "用户不存在")
    // if (!user) {
    //     ctx.throw(422, "用户不存在");
    // }
    // 2. 校验密码
    const isValid = bcrypt.compareSync(password, user.password)
    ctx.assert(isValid, 422, "密码错误")
    // if (!isValid) {
    //     ctx.throw(422, "密码错误");
    // }
    // 3. 返回token
    const token = jwt.sign({ id: user._id }, "secret")

    ctx.body = token
})

module.exports = router